﻿import socket
import threading
from openpyxl import *
import time
import os
import configparser
class empower(threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
    def run(self):
        list1=[]
        PZ=configparser.ConfigParser()
        while(True):
            PZ.read(e_path)
            value=PZ.items('端口配置')
            for i in value:
                if i not in list1 and i[1]!="端口号":
                    print(i)
                    list1.append(i)
                    cls=MyThread(i[1],i[0],int(i[1]))
                    cls.start()
                    Groups[i[1]]=cls
            time.sleep(1.5)
class MyThread(threading.Thread):
    def __init__(self, threadID, name,prot):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.prot=prot
        self.statue=False
    def run(self):
        receive_data(self.prot)
def receive_data(prot):
    list_all=[]
    list=[]
    BUFSIZE = 1024
    ip_port = ('127.0.0.1', prot)
    print(prot)
    server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # udp协议
    server.bind(ip_port)
    while True:
        global d
        d,client_addr = server.recvfrom(BUFSIZE)
        data=d.decode('gbk')
        print(data)
        menu,command,information=analysis_data(data)
        if menu=='1':
            class_admin(command,information,prot,server)
        elif menu=='2' :
            print('---------------------------')
            a=learn_credit(command,information,prot,list,list_all,server)
            a.data_processing()
def analysis_data(data):
    list=data.split('/')
    print(list)
    menu=list[0]
    command=list[1]
    information=list[2]
    return ((menu,command,information))
# 班级管理（1）
class class_admin():
    def __init__(self,command,data,prot,server):
        self.command=command
        self.data=data
        self.prot=prot
        self.server=server
        if self.command=='I' or self.command=='P':
            self.init_class()
        elif self.command=='N' or self.command=='H':
            self.change_class()
    def init_class(self):
        if self.command=='I':
            path=cls_path+'\\'+self.data
            file=path+'\\'+self.data+'.ini'
            try:
                os.mkdir(path)
                wb=Workbook()
                wb.save(path+'\\'+self.data+'.xlsx')
            except BaseException as e:
                print(e)
                print('存在该班级,{0}创建失败'.format(self.data))
            PZ=configparser.ConfigParser()
            PZ.add_section('成员')
            PZ.add_section('逻辑控制')
            PZ.set('逻辑控制','活动开关','真')
            PZ.set('逻辑控制','类型开关','假')
            PZ.set('逻辑控制','学时开关','假')
            PZ.set('逻辑控制','证明开关','假')
            PZ.set('逻辑控制','地点开关','假')
            PZ.set('逻辑控制','成员开关','假')
            with open(file,'w') as f:
                PZ.write(f)
            self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
        elif self.command=='P':
            self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
    def change_class(self):
        if self.command=='N':
            pass
        elif self.command=='H':
            pass
# 学时管理（2）
class learn_credit():
    def __init__(self,command,data,port,list,list_all,server):
        self.prot=port
        self.data=data
        self.command=command
        self.list=list
        self.list_all=list_all
        self.server=server
    # 接受数据处理分类

    def data_processing(self):
        s=configparser.ConfigParser()
        s.read(e_path)
        self.cls=s.get('班级配置',str(self.prot))
        level={'证书证明':'校级',
               '学校证明':'校级',
               '学院证明':'院级'}
        act_time=time.strftime('%Y-%m-%d',time.localtime(time.time()))
        if self.command=='A':
            learn_credit.act=self.data
            print(self.prot,self.command,self.data)
            self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
        elif self.command=='T':
            learn_credit.type=self.data
            print(self.prot,self.command,self.data)
            self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
        elif self.command=='S':
            try:
                learn_credit.score=int(self.data)
                print(self.prot,self.command,self.data)
            except:
                learn_credit.score='NULL'
            finally:
                self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
        elif self.command=='L':
            learn_credit.prove=self.data
            self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
        elif self.command=='D':
            learn_credit.place=self.data
            self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
        elif self.command=='P':
            print("已经进入P中")
            s=configparser.ConfigParser()
            s.read(e_path)
            s.read(cls_path+"/"+self.cls+'/'+self.cls+'.ini')
            number=s.get('成员',self.data)
            people=self.data
            try:
                dict=[people,
                      '数学与系统科学学院',
                      self.cls,
                      number,
                      learn_credit.type,
                      level[learn_credit.prove],
                      learn_credit.act,
                      act_time,
                      learn_credit.place,
                      learn_credit.score,
                      learn_credit.prove
                     ]
            except BaseException as e:
                dict=[]
                print(e)
            if dict not in self.list_all:
                self.list.append(dict)
                self.list_all.append(dict)
            self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
        elif self.data=='结束':
            print(self.prot,self.command,self.data)
            self.xlsx_processing()
            self.server.sendto('ok'.encode('utf-8'),("127.0.0.1",18522))
    # 数据转表格
    def xlsx_processing(self):
        sheet_time=time.strftime('%Y-%m',time.localtime(time.time()))
        wb=load_workbook(cls_path+"\\"+self.cls+'\\'+self.cls+'.xlsx')
        # 按月创建新表单
        try:
            ws=wb[sheet_time]
            if ws['A1']!="姓名":
                ws.append(['姓名','学院','班级','学号','类别','级别','活动','时间','地点','学时','证明方式'])
            print('已存在表单{0}'.format(sheet_time))
        except:
            wb.create_sheet(sheet_time)
            ws=wb[sheet_time]
            print('新建表单{0}'.format(sheet_time))
            ws.append(['姓名','学院','班级','学号','类别','级别','活动','时间','地点','学时','证明方式'])
            print('已经append')
            self.list_all.clear()
        for i in self.list:
            ws.append(i)
            print(i)
        try:
            wb.save(cls_path+"\\"+self.cls+"\\"+self.cls+'.xlsx')
        except BaseException as e:
            print(e)
        finally:
            self.list.clear()
# 活动信息修改（3）
class active_change():
    def __init__(self,data):
        self.data=data
    def active_delete(self):
        pass
    def member_delete(self):
        pass
    def member_add(self):
        pass
if __name__=="__main__":
    cls_path=r'D:\E_language\project\QQMini\测试文件\cls'
    e_path=r'D:\E_language\project\QQMini\测试文件\ALL.ini'
    Groups={}
    t1=empower(1,'SC')
    t1.start()

